/**
 * Represents currently displayed dialog
 */
app.dialog = {
	// Dialog object
	_currentDialog : null,
	// Current dialog step
	_currentStep : '',
	// Dialog container object
	_container : null,
	// Dialog text object
	_text : null,
	// Dialog actions container object
	_actions : null,
	
	/**
	 * Init dialog module
	 */
	init : function() {
		this._container = $('#panel_dialog');
		this._text = $('#dialogText').empty();
		this._actions = $('#dialogActions ul').empty();
	},
	
	/**
	 * Start new dialog
	 *
	 * @param id Dialog ID
	 */
	start : function(id) {
		this._currentDialog = app.DialogFactory.get(id);
		
		this.showStep('default');
		
		app.area.add2stage(this._container);
	},
	
	/**
	 * Show dialog step
	 *
	 * @param id Dialog step ID
	 */
	showStep : function(id) {
		var that = this;
		this._currentStep = id;
		this._text.html(this._currentDialog[this._currentStep].text);
		this._actions.empty();
		
		$.each(this._currentDialog[this._currentStep].actions, function(id, action) {
			var a = $('<a>').attr({
				title : action,
				href : '#' + id
			}).text(action).click(function() {
				if (id != 'close') {
					that.showStep(id);
				}
				else {
					that.close();
				}
				
				return false;
			});
			
			$('<li>').append(a).appendTo(that._actions);
		});
	},
	
	/**
	 * Finish and close current dialog
	 */
	close : function() {
		this._container.appendTo('#panels');
	}
};

/**
 * Dialog Factory
 */
app.DialogFactory = {
	// Dialogs list
	_dialogs : [],
	
	/**
	 * Load dialogs list
	 *
	 * @param list Associative array of dialogs
	 */
	load : function(list) {
		var that = this;
		
		$.each(list, function(id, dialog) {
			for (var step in dialog) {
				if (!dialog[step].actions) {
					dialog[step].actions = {};
				}
				
				if (!dialog[step].actions.close) {
					dialog[step].actions.close = 'Close';
				}
			};
			
			that._dialogs[id] = dialog;
		});
	},
	
	/**
	 * Get a dialog from cache
	 *
	 * @param id Dialog ID
	 * @return Dialog object
	 */
	get : function(id) {
		return this._dialogs[id];
	}
};

/**
 * Data
 */
(function() {
	var dialogs = {
		'sage1' : {
			'default' : {
				text : 'First step',
				actions : {'step2' : 'Step2'}
			},
			'step2' : {
				text : 'Step 2 description',
				actions : {'close' : 'End dialog'}
			}
		}
	};
	
	app.DialogFactory.load(dialogs);
})();